﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Text;
using System.Security.Cryptography;
using WxApiLib;
using System.Net;
using System.IO;


namespace FuYouWX.Controllers.Home
{
    public class HomeController : Controller
    {
        //
        // GET: /Home/
        string token = "manjia";

        string menusurl = "https://api.weixin.qq.com/cgi-bin/menu/create?access_token=";

        //string POSTURL = "http://file.api.weixin.qq.com/cgi-bin/media/upload?access_token=";
        static string tokenurl = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential";

        static string ticketurl = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?";

        //
        public static string jsapi_ticket = "";
        public static DateTime ticketDateTime;

        //检查jsapi_ticket
        public static string CheckJsapi_ticket()
        {
            if (ticketDateTime.AddHours(1.5) < DateTime.Now || string.IsNullOrEmpty(jsapi_ticket))    //每隔2小时执行一次
            {
                return Get_jsapi_ticket();
            }
            return jsapi_ticket;
        }

        //获取jsapi_ticket
        public static string Get_jsapi_ticket()
        {
            WebClient wc = new WebClient();
            string url = string.Format(ticketurl + "&access_token=" + CheckAccess_token() + "&type=jsapi");
            byte[] buff = wc.DownloadData(url);
            string content = Encoding.UTF8.GetString(buff);
            string[] temp = content.Split(',');
            //   Response.Write(content);
            string[] tp = temp[2].Split(':');
            content = tp[1].ToString().Replace('"', ' ').Trim();

            jsapi_ticket = content;
            ticketDateTime = DateTime.Now;
            return jsapi_ticket;
        }

        public void ReturnData() 
        {
            string Action = Request.QueryString["Action"];
            string data = Request.QueryString["Data"];
            string result = "{\"msg\":\"" + Action + "\",\"aaa\":\"" + data + "\"}";
            Response.Write(result);
        }

        //公众号信息
        public static string appid = "wx796039b9d2b16ff6";
        static string APPSECRET = "a5ba33ffe8abdc9e772d72d7f08ff675";

        public static string access_token = "";
        public static DateTime tokenDateTime;

        // config接口注入权限验证的时间戳
        public string timestamp = "";

        // config接口注入权限验证的随机数
        public string echostr = "";

        //页面加载之前进入
        public ActionResult Index()
        {
            //jsapi_ticket = CheckJsapi_ticket();

            #region 签名验证
            if (Request.HttpMethod.ToUpper() == "GET")
            {
                // 微信加密签名    
                string signature = Request.QueryString["signature"];
                // 时间戳    
                timestamp = Request.QueryString["timestamp"];
                // 随机数    
                string nonce = Request.QueryString["nonce"];
                // 随机字符串    
                echostr = Request.QueryString["echostr"];

                if (CheckSignature(signature, timestamp, nonce))
                {
                    NetLog.WriteTextLog("OK", Request.Url.AbsoluteUri + "   " + Request.HttpMethod + "  " + token, DateTime.Now, "签名验证");
                    //Response.Write(echostr);
                    //Response.End();

                }
                else
                {
                    NetLog.WriteTextLog("失败", Request.Url.AbsoluteUri + "   " + Request.HttpMethod, DateTime.Now, "签名验证");
                    //Response.Write("请求失败!");
                    //Response.End();
                }
            }
            #endregion

            //GeneratesMenu();

            #region 自动回复
            string weixin = "";
            weixin = PostInput();//获取xml数据
            NetLog.WriteTextLog("处理消息请求", weixin, DateTime.Now, "处理消息请求");
            if (!string.IsNullOrEmpty(weixin))
            {
                //调用消息适配器,处理消息请求
                Common c = new Common();
                //异步处理消息请求
                string responseMsg = c.ResponseMsg(weixin);
                System.Web.HttpContext.Current.Response.Clear();
                System.Web.HttpContext.Current.Response.Charset = "UTF-8";
                System.Web.HttpContext.Current.Response.Write(responseMsg);
                System.Web.HttpContext.Current.Response.End();
            }
            #endregion

            return View();
        }

        //生成菜单
        public void GeneratesMenu() 
        {
            #region  生成菜单
            string access_token = CheckAccess_token();
            //Response.Write(access_token);
            //3、创建菜单
            var result = PostReqest(menusurl + access_token, GetWXMenuStr());
            //Response.Write(result);
            //NetLog.WriteTextLog("" + result + "", access_token, DateTime.Now, "生成菜单");
            #endregion
        }

        //获取xml数据
        private string PostInput()
        {
            Stream s = System.Web.HttpContext.Current.Request.InputStream;
            NetLog.WriteTextLog("HttpContext.Current.Request.InputStream", s.ToString(), DateTime.Now);
            byte[] b = new byte[s.Length];
            NetLog.WriteTextLog("new byte[s.Length]", b.ToString(), DateTime.Now);
            s.Read(b, 0, (int)s.Length);
            NetLog.WriteTextLog("Encoding.UTF8.GetString(b)", Encoding.UTF8.GetString(b), DateTime.Now);
            return Encoding.UTF8.GetString(b);
        }

        private bool CheckSignature(String signature, String timestamp, String nonce)
        {
            String[] arr = new String[] { token, timestamp, nonce };
            // 将token、timestamp、nonce三个参数进行字典序排序    
            Array.Sort<String>(arr);

            StringBuilder content = new StringBuilder();
            for (int i = 0; i < arr.Length; i++)
            {
                content.Append(arr[i]);
            }

            String tmpStr = SHA1_Encrypt(content.ToString());


            // 将sha1加密后的字符串可与signature对比，标识该请求来源于微信    
            return tmpStr != null ? tmpStr.Equals(signature) : false;
        }

        /// <summary>  
        /// 使用缺省密钥给字符串加密  
        /// </summary>  
        /// <param name="Source_String"></param>  
        /// <returns></returns>  
        private string SHA1_Encrypt(string Source_String)
        {
            byte[] StrRes = Encoding.Default.GetBytes(Source_String);
            HashAlgorithm iSHA = new SHA1CryptoServiceProvider();
            StrRes = iSHA.ComputeHash(StrRes);
            StringBuilder EnText = new StringBuilder();
            foreach (byte iByte in StrRes)
            {
                EnText.AppendFormat("{0:x2}", iByte);
            }
            return EnText.ToString();
        }

        //检查access_token
        public static string CheckAccess_token()
        {
            if (tokenDateTime.AddHours(1.5) < DateTime.Now || string.IsNullOrEmpty(access_token))    //每隔2小时执行一次
            {
                return Get_access_token();
            }
            return access_token;
        }

        //获取access_token
        public static string Get_access_token()
        {
            WebClient wc = new WebClient();
            string url = string.Format(tokenurl + "&appid=" + appid + "&secret=" + APPSECRET);
            byte[] buff = wc.DownloadData(url);
            string content = Encoding.UTF8.GetString(buff);
            string[] temp = content.Split(',');

            //   Response.Write(content);

            string[] tp = temp[0].Split(':');
            content = tp[1].ToString().Replace('"', ' ').Trim();

            access_token = content;
            tokenDateTime = DateTime.Now;
            return access_token;
        }

        //获取输入的菜单信息
        public string GetWXMenuStr()
        {
            System.Text.StringBuilder sb = new StringBuilder();

            sb.AppendLine("{");
            sb.AppendLine("\"button\":[");
            sb.AppendLine("{");
            sb.AppendLine("\"name\":\"福优商城\",");
            sb.AppendLine("\"sub_button\":[");
            sb.AppendLine("{");
            sb.AppendLine("\"type\":\"view\",");
            sb.AppendLine("\"name\":\"福优商城\",");
            sb.AppendLine("\"url\":\"http://120.26.130.90/Vshop/default.aspx\"");
            sb.AppendLine("},");

            sb.AppendLine("{");
            sb.AppendLine("\"type\":\"view\",");
            sb.AppendLine("\"name\":\"电影票\",");
            sb.AppendLine("\"url\":\"http://120.26.130.90/Vshop/SpiderIndex.aspx\"");
            sb.AppendLine("},");

            sb.AppendLine("{");
            sb.AppendLine("\"type\":\"click\",");
            sb.AppendLine(" \"name\":\"安卓APP\",");
            sb.AppendLine(" \"key\":\"ABOUT\"");
            sb.AppendLine("}]");
            sb.AppendLine("},");

            sb.AppendLine("{");
            sb.AppendLine("\"name\":\"福优服务\",");
            sb.AppendLine("\"sub_button\":[");
            sb.AppendLine("{");
            sb.AppendLine("\"type\":\"view\",");
            sb.AppendLine("\"name\":\"信用卡充值\",");
            sb.AppendLine("\"url\":\"http://120.26.130.90/Vshop/BindCreditCard.aspx\"");
            sb.AppendLine("},");

            sb.AppendLine("{");
            sb.AppendLine("\"type\":\"view\",");
            sb.AppendLine("\"name\":\"话费充值\",");
            sb.AppendLine("\"url\":\"http://120.26.130.90/Vshop/PhoneRecharge.aspx\"");
            sb.AppendLine("},");

            sb.AppendLine("{");
            sb.AppendLine("\"type\":\"view\",");
            sb.AppendLine("\"name\":\"加油卡充值\",");
            sb.AppendLine("\"url\":\"http://120.26.130.90/Vshop/FuelCard.aspx\"");
            sb.AppendLine("},");

            sb.AppendLine("{");
            sb.AppendLine("\"type\":\"view\",");
            sb.AppendLine(" \"name\":\"优分充值\",");
            sb.AppendLine(" \"url\":\"http://120.26.130.90/Vshop/OptimalRecharge.aspx\"");
            sb.AppendLine("}]");
            sb.AppendLine("},");

            sb.AppendLine("{");
            sb.AppendLine("\"name\":\"我的福优\",");
            sb.AppendLine("\"sub_button\":[");
            sb.AppendLine("{");
            sb.AppendLine("\"type\":\"view\",");
            sb.AppendLine("\"name\":\"我的交易\",");
            sb.AppendLine("\"url\":\"http://120.26.130.90/Vshop/TransactionRecord.aspx\"");
            sb.AppendLine("},");
            sb.AppendLine("{");
            sb.AppendLine("\"type\":\"view\",");
            sb.AppendLine("\"name\":\"我的优分\",");
            sb.AppendLine("\"url\":\"http://120.26.130.90/api/WxSend.ashx\"");
            sb.AppendLine("},");

            sb.AppendLine("{");
            sb.AppendLine("\"type\":\"view\",");
            sb.AppendLine("\"name\":\"账号注册\",");
            sb.AppendLine("\"url\":\"http://120.26.130.90/Vshop/AccountRegister.aspx\"");
            sb.AppendLine("},");

            sb.AppendLine("{");
            sb.AppendLine("\"type\":\"view\",");
            sb.AppendLine("\"name\":\"登录/解绑\",");
            sb.AppendLine("\"url\":\"http://120.26.130.90/vshop/login.aspx\"");
            sb.AppendLine("}]");
            sb.AppendLine("}]");
            sb.AppendLine(" }");

            string weixin1 = sb.ToString();

            return weixin1;
        }

        // 创建菜单
        public string PostReqest(string posturl, string menu)
        {
            string str = string.Empty;
            try
            {
                byte[] byteArray = Encoding.UTF8.GetBytes(menu);
                HttpWebRequest req = (HttpWebRequest)WebRequest.Create(new Uri(posturl));
                req.Method = "POST";
                req.ContentType = "application/x-www-form-urlencoded";
                req.ContentLength = byteArray.Length;

                Stream stream = req.GetRequestStream();
                stream.Write(byteArray, 0, byteArray.Length);
                stream.Close();

                HttpWebResponse resp = (HttpWebResponse)req.GetResponse();

                StreamReader sr = new StreamReader(resp.GetResponseStream(), Encoding.Default);
                str = sr.ReadToEnd();

                sr.Close();
                resp.Close();
                stream.Close();

            }
            catch { }

            return str;
        }

    }
}
